<?php
// Target backup functions work by Thursday 22/11/07
// Target restore functions work by Friday 23/11/07
// Target web-cp release next week
// Module Body

function backups_cfg(&$cfg) {
}

// Setup menu
// Personal backups have no use until more user
// varieties exist, e.g. db user and hooks exist for users
function backups_menu(&$data) {
	global $menu;
	$menu['domain'][] = 'backups';
	$menu['reseller'][] = 'backups';
}

function backups_lang(&$data) {
	global $T;
	switch($data['lang']) {
		default:
			$T['menu']['backups']	= 'Backups';

			$T['Local'] = "Local";
			$T['Remote'] = "Remote";
			$T['Files'] = "Files";
			$T['Backup Files'] = "Include all files under these domains' root directory.";
			$T['Email'] = "Email";
			$T['Backup Email'] = "Include all email belonging to accounts on these domains.";
			$T['Databases'] = "MySQL Databases";
			$T['Backup Databases'] = "Include all databases belonging to accounts on these domains.";
			$T['Local Placement'] = "Place the backup archive on this web server.";
			$T['Remote Placement'] = "Upload the backup archive to the server specified below.";
			$T['FTP Server'] = "FTP Server";
			$T['Username'] = "Username";
			$T['Password'] = "Password";
			$T['Directory'] = "Directory";
			$T['Create Backup'] = "Create Backup";
			$T['Backup Started for'] = "Backup Started for Selected Items";
			$T['Select Users'] = "Select users to include";
			$T['Select Domains'] = "Select domains to include";
			$T['Select Contents'] = "Select Contents";
			$T['Select Location'] = "Select Location";
			$T['Backup Functions'] = "Backup Functions";
			$T['Create Backup Description'] = "Create a new backup - scheduled or immediate.";
			$T['Delete Backup'] = "Delete Backup";
			$T['Delete Backup Description'] = "Delete an existing scheduled backup.";
			$T['Restore Backup'] = "Restore Backup";
			$T['Restore Backup Description'] = "Restore a local or remote backup, overwriting current data.";
			$T['Select Scheduled Backups'] = "Select Scheduled Backups";
			$T['Select Local Backup'] = "Select Local Backup";
			$T['Delete Backups'] = "Delete Backup(s)";
			$T['Confirm Delete Backups'] = "Are you sure you wish to delete these backups?";
			$T['Selected Backups Deleted'] = "Selected Backups Deleted";
			$T['Selected Backups Restored'] = "Selected Backups Restoration Initiated";
			$T['Restore Backups'] = "Restore Backup(s)";
			$T['Confirm Restore Backups'] = "Are you sure you wish to restore these backups, overwriting all files?";
			$T['Domain Name'] = "Domain Name";
			$T['Frequency'] = "Frequency";
			$T['MySQL'] = "MySQL";
			$T['Files'] = "Domain Files";
			$T['Email'] = "Domain Email";
			$T['Remote'] = "Remote";
			$T['Local'] = "Local";
			$T['Owner'] = "Owner";
			$T['Select Type'] = "Select Type";
			$T['Immediate'] = "Immediate";
			$T['Scheduled'] = "Scheduled";
			$T['Backup Immediate'] = "Generate this backup now.";
			$T["Daily"] = "Daily";
			$T["Weekly"] = "Weekly";
			$T["Monthly"] = "Monthly";
			$T['File Name'] = "File Name";
			$T['File Size'] = "File Size";
			$T['Contents'] = "Contents";
			$T['Upload Remote Backups'] = "Upload Remote Backup";
			$T['Upload Backup'] = "Upload Backup";
			$T['Selected Backup Uploaded'] = "Selected Backup Uploaded";
			break;
	}
}

// Backups domain panel
// Creates and manages backups of single domains
function backups_domain(&$data) {
//Global required cfg
global $cfg, $T;

// Get vars
$cp = $data['_cp'];
$url = $data['_url'];
$current_url = $data['_current_url'];
// Form processing
$action = $data['_action'];
$confirm = $data['_confirm'];
// User and Domain Info
$userdata = $data['_userdata'];
$domaindata = $data['_domaindata'];

// For upload - use file manager functions - make file manager
// module from existing one
$domain = load_input_vars('domain',1,0,0);

// If data is set (i.e the submit button has been hit)
if (isset($data) && $userdata['type'] != 'demo') {
	switch ($data['action']) {
		case 'create':

				// Run backup
				$error = backups_create('domain', $domaindata['domain'], $data['contents'], $data['location'], $data['schedule']);

				// If an error is encountered then display message else display success
				if ($error) {
					echo "<br>&nbsp;&nbsp;".implode("<br>\n&nbsp;&nbsp;",$error)."<br>\n<br>";
				} else {
					unset($data);
					unset($data['users']);
					echo "<br><div align='center'><b>".$T['Backup Started for']."</b></div><br>\n";
				}

			break;
		case 'delete':
			if (is_array($data['backups'])) {
				// remove spaces and slashes.
				while (list($key, $val) = each($data))
					$data[$key] = trim(stripslashes($val));

				// If a command is sent to delete a backup then go ahead
				if ($data['deletebackup'] == "yes") {
					$error = backups_delete("sched", $data['backups']);


				// If an error is encountered then display message else display success
				if ($error) {
					echo "<br>&nbsp;&nbsp;".implode("<br>\n&nbsp;&nbsp;",$error)."<br>\n<br>";
				} else {
					unset($data);
					unset($data['backups']);
					echo "<br><div align='center'><b>".$T['Selected Backups Deleted']."</b></div><br>\n";
				}
				}

			}
			break;
		case 'deletelocal':
			if (is_array($data['backups'])) {
				// If a command is sent to delete a backup then go ahead
				if ($data['deletebackup'] == "yes") {
					$error = backups_delete("local", $data['backups']);


				// If an error is encountered then display message else display success
				if ($error) {
					echo "<br>&nbsp;&nbsp;".implode("<br>\n&nbsp;&nbsp;",$error)."<br>\n<br>";
				} else {
					unset($data);
					unset($data['backups']);
					echo "<br><div align='center'><b>".$T['Selected Backups Deleted']."</b></div><br>\n";
				}
				}

			}
			break;
		case 'restore':

			// If a command is sent to restore a backup then go ahead
			if ($data['restorebackup'] == "yes") {
				$error = backups_restore("domain", $data['backup'], $data['contents'], $data['location']);

				// If an error is encountered then display message else display success
				if ($error) {
					echo "<br>&nbsp;&nbsp;".implode("<br>\n&nbsp;&nbsp;",$error)."<br>\n<br>";
				} else {
					unset($data);
					unset($data['backups']);
					echo "<br><div align='center'><b>".$T['Selected Backups Restored']."</b></div><br>\n";
				}
			}
			break;
		case 'upload':
			$filename = $_FILES['backupfile']['name'];
			$error = is_uploaded_file($_FILES['backupfile']['tmp_name']);
			copy($_FILES['backupfile']['tmp_name'], $cfg['webdir']."/".$domain."/_backups/".$filename);
			// is_uploaded_file returns true if the file was uploaded via HTTP_POST
			// so normally true should be returned
			if (!$error) {
				echo "<br>&nbsp;&nbsp;".$error."<br>\n<br>";
			} else {
				unset($backupfile);
				unset($domain);
				echo "<br><div align='center'><b>".$T['Selected Backup Uploaded']."</b></div><br>\n";
			}
			break;
	}
} elseif (isset($data) && $userdata['type'] == 'demo') {
	echo "<center>".$T['err']['demo user']."</center>";
}
?>
<table align="center" cellpadding="0" cellspacing="1" width="500" class="tblbg">
	<tr class="tbltop">
		<td colspan="3">&nbsp;<? echo $T['Backup Functions']; ?>&nbsp;</td>
	</tr>
	<tr class="row1">
		<td width="110" align="right"><b><a href='<?=$current_url;?>&action=add'><?=$T['Create Backup'];?></a>&nbsp;</td><td align=left colspan=2><? echo $T['Create Backup Description']; ?></td>
	</tr>
	<tr class="row2">
		<td width="110" align="right"><b><a href='<?=$current_url;?>&action=del'><?=$T['Delete Backup'];?></a>&nbsp;</td><td align=left colspan=2><? echo $T['Delete Backup Description']; ?></td>
	</tr>
	<tr class="row1">
		<td width="110" align="right"><b><a href='<?=$current_url;?>&action=res'><?=$T['Restore Backup'];?></a>&nbsp;</td><td align=left colspan=2><? echo $T['Restore Backup Description']; ?></td>
	</tr>
</table>
<br>
<br>
<?
switch ($action) {
	case "add":
?>
<form action="<?=$current_url;?>" method="post" name="webcp" onSubmit="submitonce(this);">
<input type="hidden" name="data[action]" value="create">
<input type="hidden" name="action" value="add">
<input type="hidden" name="data[createbackup]" value="yes">
<table align="center" cellpadding="0" cellspacing="1" width="500" class="tblbg">
	<tr class="tbltop">
		<td colspan="3"><b>&nbsp;<? echo $T['Select Type']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row1">
		<td width="30" align="center">
			<input type="radio" name="data[schedule][type]" value="scheduled" <? if ($data['schedule']['type'] == "scheduled") { echo "checked"; }?>>
		</td>
		<td align="left" width="100">
			<b><? echo $T['Scheduled']; ?></b></td>
		<td>
			<select name="data[schedule][recurrance]">
				<option value=''>Please Select</option>
				<option value='1'<? if ($data['schedule']['recurrance'] == "1") { echo "selected"; }?>><?=$T["Daily"];?></option>
				<option value='2'<? if ($data['schedule']['recurrance'] == "2") { echo "selected"; }?>><?=$T["Weekly"];?></option>
				<option value='3'<? if ($data['schedule']['recurrance'] == "3") { echo "selected"; }?>><?=$T["Monthly"];?></option>
			</select>
		</td>
	</tr>
	<tr class="row2">
		<td width="30" align="center">
			<input type="radio" name="data[schedule][type]" value="immediate" <? if ($data['schedule']['type'] != "scheduled") { echo "checked"; }?>>
		</td>
		<td align="left"><b><? echo $T['Immediate']; ?></b></td>
		<td><? echo $T['Backup Immediate']; ?></td>
	</tr>
</table>

<br>
<table align="center" cellpadding="0" cellspacing="1" width="500" class="tblbg">
	<tr class="tbltop">
		<td colspan="3"><b>&nbsp;<? echo $T['Select Contents']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row1">
		<td width="30" align="center"><input type="checkbox" name="data[contents][files]" <? if ($data['contents']['files'] == "on") { echo "checked"; }?>></td><td align=left><b><? echo $T['Files']; ?></b></td><td><? echo $T['Backup Files']; ?></td>
	</tr>
	<tr class="row2">
		<td width="30" align="center"><input type="checkbox" name="data[contents][email]" <? if ($data['contents']['email'] == "on") { echo "checked"; }?>></td><td align=left><b><? echo $T['Email']; ?></b></td><td><? echo $T['Backup Email']; ?></td>
	</tr>
	<tr class="row1">
		<td width="30" align="center"><input type="checkbox" name="data[contents][databases]" <? if ($data['contents']['databases'] == "on") { echo "checked"; }?>></td><td align=left><b><? echo $T['Databases']; ?></b></td><td><? echo $T['Backup Databases']; ?></td>
	</tr>

	<tr class="tbltop">
		<td colspan="3">&nbsp;<b><? echo $T['Select Users']; ?></b>&nbsp;</td>
	</tr>

		<?

		$sql_query = "SELECT username, id FROM users WHERE id='".$domaindata['id']."' AND action != 'remove' ORDER BY level,username";
		$dbp = mysql_query($sql_query);

		$curclass = "row2";

		// Loop over domain users
		for($i = 0; $row = mysql_fetch_array($dbp); $i++) {

			if ($curclass == "row2")
				$curclass = "row1";
			else
				$curclass = "row2";

		$tmp_data['id'] = $row['id'];
		$tmp_data['username'] = $row['username'];
		call_hook('user:get:username', $tmp_data);

		?>

		<tr class="<? echo $curclass; ?>">
			<td width="30" align="center">
				<input type="checkbox" name="data[contents][users][]" value='<? echo $tmp_data["username"]; ?>' <? if (is_array($data['contents']['users']) && in_array($tmp_data["username"], $data['contents']['users'])) { echo "checked"; }?>>
			</td>
			<td align="left" colspan="2"><b><? echo $tmp_data["username"]; ?></b></td>
		</tr>

		<?	// End loop
		} ?>

</table>
<br>
<table align="center" cellpadding="0" cellspacing="1" width="500" class="tblbg">
	<tr class="tbltop">
		<td colspan=3><b>&nbsp;<? echo $T['Select Location']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row1">
		<td width=30 align=center><input type="checkbox" name="data[location][local]" <? if ($data['location']['local'] == "on") { echo "checked"; }?>></td><td align=left><b><? echo $T['Local']; ?></b></td><td><? echo $T['Local Placement']; ?></td>
	</tr>
	<tr class="row2">
		<td width=30 align=center><input type="checkbox" name="data[location][remote]" <? if ($data['location']['remote'] == "on") { echo "checked"; }?>></td><td align=left><b><? echo $T['Remote']; ?></b></td><td><? echo $T['Remote Placement']; ?></td>
	</tr>
	<tr class="row2">
		<td></td><td align=right><b><? echo $T['FTP Server']; ?>: </b></td><td><input type="textbox" name="data[location][server]" value="<? if (empty($data['location']['server'])) echo '127.0.0.1'; else echo $data['location']['server']; ?>"></td>
	</tr>
	<tr class="row2">
		<td></td><td align=right><b><? echo $T['Username']; ?>: </b></td><td><input type="textbox" name="data[location][username]" value="<? echo $data['location']['username']; ?>"></td>
	</tr>
	<tr class="row2">
		<td></td><td align=right><b><? echo $T['Password']; ?>: </b></td><td><input type="password" name="data[location][password]" value="<? echo $data['location']['password']; ?>"></td>
	</tr>
	<tr class="row2">
		<td></td><td align=right><? echo $T['Directory']; ?>: </td><td><input type="textbox" name="data[location][directory]" value="<? echo $data['location']['directory']; ?>"></td>
	</tr>
</table><br>
<div align="center"><input type="submit" value="<? echo $T['Create Backup']; ?>"></div>
</form>
</div>
<?
	break;
	case "del":
	$SQL = "SELECT backups.id as backid, backups.domain, backups.recurrance, backups.files, backups.email, backups.remote, backups.local, backups.cpusername FROM backups INNER JOIN domains on backups.domain = domains.domain WHERE domains.domain='".$domaindata['domain']."' ORDER BY backups.domain";
	$selfres = mysql_query($SQL);
?>
<form action="<?=$current_url;?>" method="post" name="webcp" onSubmit="submitonce(this);">
<input type="hidden" name="data[action]" value="delete">
<input type="hidden" name="action" value="del">
<input type="hidden" name="data[deletebackup]" value="yes">
<table align="center" cellpadding="0" cellspacing="1" width="600" class="tblbg">
	<tr class="tbltop">
		<td colspan=9><b>&nbsp;<? echo $T['Select Scheduled Backups']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row2">
		<td></td>
		<td><i><?=$T['Contents'];?></i></td>
		<td align="center"><i><?=$T['Frequency'];?></i></td>
		<td align="center"><i><?=$T['Files'];?></i></td>
		<td align="center"><i><?=$T['Email'];?></i></td>
		<td align="center"><i><?=$T['Remote'];?></i></td>
		<td align="center"><i><?=$T['Local'];?></i></td>
		<td align="center"><i><?=$T['Owner'];?></i></td>
	</tr>
<?
	$backupsFound = false;
	$curclass = "row2";
	for($i = 0; $row = mysql_fetch_array($selfres); $i++) {
		$backupsFound = true;
		if ($curclass == "row2") {
			$curclass = "row1";
		} else {
			$curclass = "row2";
		}
		echo "<tr class=".$curclass."><td align=center><input type=checkbox name=data[backups][] value=".$row["backid"]."></td><td>";
		if ($row["username"] != "") {
			echo $row["username"];
		} else {
			echo $T['Databases'];
		}
		echo "</td><td align=center>".$row["recurrance"]."</td>";
		echo "<td align=center>";
		if ($row["files"]) { echo "X"; } else { echo "-"; }
		echo "</td><td align=center>";
		if ($row["email"]) { echo "X"; } else { echo "-"; }
		echo "</td><td align=center>";
		if ($row["remote"]) { echo "X"; } else { echo "-"; }
		echo "</td><td align=center>";
		if ($row["local"]) { echo "X"; } else { echo "-"; }
		echo "</td><td align=center><a href='?cp=personal&url=userinfo&user=".$row["cpusername"]."'>".$row["cpusername"]."</a></td></tr>";
	}
?>
</table>
<div align="center">
<? if ($backupsFound) { ?>
<br><input type="submit" value="<? echo $T['Delete Backups']; ?>" onclick="return confirm('<?=$T['Confirm Delete Backups'];?>');">
<? } else { ?>
None Found
<? } ?>
</div>
</form>
<form action="<?=$current_url;?>" method="post" name="webcp" onSubmit="submitonce(this);">
<input type="hidden" name="data[action]" value="deletelocal">
<input type="hidden" name="action" value="del">
<input type="hidden" name="data[deletebackup]" value="yes">
<table align="center" cellpadding="0" cellspacing="1" width="600" class="tblbg">
	<tr class="tbltop">
		<td colspan="4"><b>&nbsp;<? echo $T['Select Local Backups']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row2">
		<td></td><td><i><?=$T['Contents'];?></i></td><td><i><?=$T['File Name'];?></i></td><td align=center><i><?=$T['File Size'];?></i></td>
	</tr>
<?

	$curclass = "row2";
	$backupsFound = false;
		$dirArray = backups_dir_list($cfg['webdir']."/".$domaindata['domain']."/_backups");
		if (is_array($dirArray)) {
			for($j=0; $j<sizeOf($dirArray); $j++) {
				$backupsFound = true;
				if ($curclass == "row2") {
					$curclass = "row1";
				} else {
					$curclass = "row2";
				}
				echo "<tr class=".$curclass."><td align=center><input type=checkbox name=data[backups][] value='".$cfg['webdir']."/".$domaindata['domain']."/_backups/".$dirArray[$j]."'></td><td>".$domaindata['domain']."</td><td>".$dirArray[$j]."</td><td align=center>".return_file_size(filesize($cfg['webdir']."/".$domaindata['domain']."/_backups/".$dirArray[$j]))."</td></tr>";
		}
	}
?>
</table>
<div align="center">
<? if ($backupsFound) { ?>
<br><input type="submit" value="<? echo $T['Delete Backups']; ?>" onclick="return confirm('<?=$T['Confirm Delete Backups'];?>');">
<? } else { ?>
None Found
<? } ?>
</div>
</form>
<?
	break;
	case "res":
?>
<form action="<?=$current_url;?>" method="post" name="webcp" onSubmit="submitonce(this);">
<input type="hidden" name="data[action]" value="restore">
<input type="hidden" name="action" value="res">
<input type="hidden" name="data[restorebackup]" value="yes">
<table align="center" cellpadding="0" cellspacing="0" width="600" class="tblbg">
	<tr class="tbltop">
		<td colspan="4"><b>&nbsp;<? echo $T['Select Local Backup']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row2">
		<td></td><td><i><?=$T['Contents'];?></i></td><td><i><?=$T['File Name'];?></i></td><td align="center"><i><?=$T['File Size'];?></i></td>
	</tr>
<?

	$curclass = "row2";
	$backupsFound = false;
		$dirArray = backups_dir_list($cfg['webdir']."/".$domaindata['domain']."/_backups");
		if (is_array($dirArray)) {
			for($j=0; $j<sizeOf($dirArray); $j++) {
				$backupsFound = true;
				if ($curclass == "row2") {
					$curclass = "row1";
				} else {
					$curclass = "row2";
				}
				echo "<tr class=".$curclass."><td align=center><input type=radio name=data[backup] value='".$cfg['webdir']."/".$domaindata['domain']."/_backups/".$dirArray[$j]."'></td><td>".$domaindata['domain']."</td><td>".$dirArray[$j]."</td><td align=center>".return_file_size(filesize($cfg['webdir']."/".$domaindata["domain"]."/_backups/".$dirArray[$j]))."</td></tr>";
		}
	}
?>
</table>
<div align="center">
<? if ($backupsFound) { ?>
<br><input type="submit" value="<? echo $T['Restore Backups']; ?>" onclick="return confirm('<?=$T['Confirm Restore Backups'];?>');">
<? } else { ?>
None Found
<? } ?>
</div>
</form>
<?
$SQL = "SELECT domain FROM domains WHERE domain='".$domaindata['domain']."' AND type='domain' ORDER BY domain";
$dres = mysql_query($SQL);
?>
<Br>
<form action="<?=$current_url;?>" method="post" name="webcp" onSubmit="submitonce(this);" enctype="multipart/form-data">
<input type="hidden" name="data[action]" value="upload">
<input type="hidden" name="action" value="res">
<input type="hidden" name="data[uploadbackup]" value="yes">
<table align="center" cellpadding="0" cellspacing="1" width="600" class="tblbg">
	<tr class="tbltop">
		<td colspan="4"><b>&nbsp;<? echo $T['Upload Remote Backups']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row1">
		<td>Select a Domain: </td>
		<td>
			<select name="domain">
				<option value="">Please Select</option>
				<?
				for($i = 0; $row = mysql_fetch_array($dres); $i++) {
					echo "<option value='".$row["domain"]."'>".$row["domain"]."</option>";
				}
				?>
			</select>
		</td>
	</tr>
	<tr class="row2">
		<td>Browse to Backup: </td><td><input type="file" name="backupfile" size="30"></td>
	</tr>
</table>
<div align="center">
<br><input type="submit" value="<? echo $T['Upload Backup']; ?>">
</div>
</form>
<?
		break;
}
}

// Backups reseller panel
// Backup a single reseller account dont worry about recursion
function backups_reseller(&$data) {
//Global required cfg
global $cfg, $T;

// Get vars
$cp = $data['_cp'];
$url = $data['_url'];
$current_url = $data['_current_url'];
// Form processing
$action = $data['_action'];
$confirm = $data['_confirm'];
// User and Domain Info
$userdata = $data['_userdata'];
$domaindata = $data['_domaindata'];
$resellerdata = $data['_resellerdata'];

// For upload
$domain = load_input_vars('domain',1,0,0);

// If data is set (i.e the submit button has been hit)
if (isset($data) && $userdata['type'] != 'demo') {
	switch ($data['action']) {
		case 'create':
			if (is_array($data)) {

				$error = backups_create('reseller', $resellerdata['id'], $data['contents'], $data['location'], $data['schedule']);

				// If an error is encountered then display message else display success
				if ($error) {
					echo "<br>&nbsp;&nbsp;".implode("<br>\n&nbsp;&nbsp;",$error)."<br>\n<br>";
				} else {
					unset($data);
					unset($data['domains']);
					echo "<br><div align='center'><b>".$T['Backup Started for']."</b></div><br>\n";
				}
			}
			break;
		case 'delete':

			if (is_array($data['backups'])) {
				// remove spaces and slashes.
				while (list($key, $val) = each($data))
					$data[$key] = trim(stripslashes($val));

				// If a command is sent to delete a backup then go ahead
				if ($data['deletebackup'] == "yes") {
					$error = backups_delete("sched", $data['backups']);

				// If an error is encountered then display message else display success
				if ($error) {
					echo "<br>&nbsp;&nbsp;".implode("<br>\n&nbsp;&nbsp;",$error)."<br>\n<br>";
				} else {
					unset($data);
					unset($data['backups']);
					echo "<br><div align='center'><b>".$T['Selected Backups Deleted']."</b></div><br>\n";
				}
				}

			}
			break;
		case 'deletelocal':
			if (is_array($data['backups'])) {
				// If a command is sent to delete a backup then go ahead
				if ($data['deletebackup'] == "yes") {
					$error = backups_delete("local", $data['backups']);


				// If an error is encountered then display message else display success
				if ($error) {
					echo "<br>&nbsp;&nbsp;".implode("<br>\n&nbsp;&nbsp;",$error)."<br>\n<br>";
				} else {
					unset($data);
					unset($data['backups']);
					echo "<br><div align='center'><b>".$T['Selected Backups Deleted']."</b></div><br>\n";
				}
				}

			}
			break;
		case 'restore':
			if (is_array($data['backups'])) {

				// If a command is sent to restore a backup then go ahead
				if ($data['restorebackup'] == "yes") {
					$error = backups_restore("local", $data['backups']);

				// If an error is encountered then display message else display success
				if ($error) {
					echo "<br>&nbsp;&nbsp;".implode("<br>\n&nbsp;&nbsp;",$error)."<br>\n<br>";
				} else {
					unset($data);
					unset($data['backups']);
					echo "<br><div align='center'><b>".$T['Selected Backups Restored']."</b></div><br>\n";
				}
				}

			}
			break;
		case 'upload':
			$filename = $_FILES['backupfile']['name'];
			$error = is_uploaded_file($_FILES['backupfile']['tmp_name']);
			copy($_FILES['backupfile']['tmp_name'], $cfg['webdir']."/".$domain."/_backups/".$filename);
			// is_uploaded_file returns true if the file was uploaded via HTTP_POST
			// so normally true should be returned
			if (!$error) {
				echo "<br>&nbsp;&nbsp;".$error."<br>\n<br>";
			} else {
				unset($backupfile);
				unset($domain);
				echo "<br><div align='center'><b>".$T['Selected Backup Uploaded']."</b></div><br>\n";
			}
			break;
	}
} elseif (isset($data) && $userdata['type'] == 'demo') {
	echo "<center>".$T['err']['demo user']."</center>";
}
?>
<table align=center cellpadding=0 cellspacing=1 width=500 class="tblbg">
	<tr class="tbltop">
		<td colspan=3>&nbsp;<? echo $T['Backup Functions']; ?>&nbsp;</td>
	</tr>
	<tr class="row1">
		<td width="110" align="right"><b><a href='<?=$current_url;?>&action=add'><?=$T['Create Backup'];?></a>&nbsp;</td><td align=left colspan=2><? echo $T['Create Backup Description']; ?></td>
	</tr>
	<tr class="row2">
		<td width="110" align="right"><b><a href='<?=$current_url;?>&action=del'><?=$T['Delete Backup'];?></a>&nbsp;</td><td align=left colspan=2><? echo $T['Delete Backup Description']; ?></td>
	</tr>
	<tr class="row1">
		<td width="110" align="right"><b><a href='<?=$current_url;?>&action=res'><?=$T['Restore Backup'];?></a>&nbsp;</td><td align=left colspan=2><? echo $T['Restore Backup Description']; ?></td>
	</tr>
</table>
<br>
<br>
<?
switch ($action) {
	case "add":
?>
<form action="<?=$current_url;?>" method="post" name="webcp" onSubmit="submitonce(this);">
<input type="hidden" name="data[action]" value="create">
<input type="hidden" name="action" value="add">
<input type="hidden" name="data[createbackup]" value="yes">
<table align="center" cellpadding="0" cellspacing="1" width="500" class="tblbg">
	<tr class="tbltop">
		<td colspan="3"><b>&nbsp;<? echo $T['Select Type']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row1">
		<td width="30" align="center">
			<input type="radio" name="data[schedule][type]" value="recurring" <? if ($data['schedule']['type'] == "recurring") { echo "checked"; }?>>
		</td>
		<td align="left" width="100">
			<b><? echo $T['Scheduled']; ?></b>
		</td>
		<td>
			<select name="data[schedule][recurrance]">
			<option value=''>Please Select</option>
			<option value='1'<? if ($data['schedule']['recurrance'] == "1") { echo "selected"; }?>><?=$T["Daily"];?></option>
			<option value='2'<? if ($data['schedule']['recurrance'] == "2") { echo "selected"; }?>><?=$T["Weekly"];?></option>
			<option value='3'<? if ($data['schedule']['recurrance'] == "3") { echo "selected"; }?>><?=$T["Monthly"];?></option>
			</select>
		</td>
	</tr>
	<tr class="row2">
		<td width="30" align="center">
			<input type="radio" name="data[schedule][type]" value="immediate" <? if ($data['schedule']['type'] != "scheduled") { echo "checked"; }?>>
		</td>
		<td align="left">
			<b><? echo $T['Immediate']; ?></b>
		</td>
		<td>
			<? echo $T['Backup Immediate']; ?>
		</td>
	</tr>
</table>

<br>
<table align="center" cellpadding="0" cellspacing="1" width="500" class="tblbg">
	<tr class="tbltop">
		<td colspan="3"><b>&nbsp;<? echo $T['Select Contents']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row1">
		<td width="30" align="center"><input type="checkbox" name="data[contents][files]" <? if ($data['contents']['files'] == "on") { echo "checked"; }?>></td><td align=left><b><? echo $T['Files']; ?></b></td><td><? echo $T['Backup Files']; ?></td>
	</tr>
	<tr class="row2">
		<td width="30" align="center"><input type="checkbox" name="data[contents][email]" <? if ($data['contents']['email'] == "on") { echo "checked"; }?>></td><td align=left><b><? echo $T['Email']; ?></b></td><td><? echo $T['Backup Email']; ?></td>
	</tr>
	<tr class="row1">
		<td width="30" align="center"><input type="checkbox" name="data[contents][database]" <? if ($data['contents']['database'] == "on") { echo "checked"; }?>></td><td align=left><b><? echo $T['Database']; ?></b></td><td><? echo $T['Backup Databases']; ?></td>
	</tr>

	<tr class="tbltop">
		<td colspan="3"><b>&nbsp;<? echo $T['Select Domains']; ?>&nbsp;</b></td>
	</tr>
	<?

	$sql_query = "SELECT domain,id FROM domains WHERE owner=".$resellerdata['id']." AND type='domain' AND action != 'remove' ORDER BY priority,domain";
	$dbp = mysql_query($sql_query);

	$curclass = "row2";

	for($i = 0; $row = mysql_fetch_array($dbp); $i++) {
		if ($curclass == "row2") {
			$curclass = "row1";
		} else {
			$curclass = "row2";
		}

	?>
	<tr class="<? echo $curclass; ?>">
		<td width="30" align="center">
			<input type="checkbox" name="data[contents][domains][]" value='<? echo $row["id"]; ?>' <? if (is_array($data['contents']['domains']) && in_array($row["id"], $data['contents']['domains'])) { echo "checked"; }?>>
		</td>
		<td align="left" colspan="2"><b><? echo $row["domain"]; ?></b></td>
	</tr>

	<?	// End loop
	} ?>

</table>
<br>
<table align="center" cellpadding="0" cellspacing="1" width="500" class="tblbg">
	<tr class="tbltop">
		<td colspan=3><b>&nbsp;<? echo $T['Select Location']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row1">
		<td width=30 align="center"><input type="checkbox" name="data[location][local]" <? if ($data['location']['local'] == "on") { echo "checked"; }?>></td><td align=left><b><? echo $T['Local']; ?></b></td><td><? echo $T['Local Placement']; ?></td>
	</tr>
	<tr class="row2">
		<td width=30 align="center"><input type="checkbox" name="data[location][remote]" <? if ($data['location']['remote'] == "on") { echo "checked"; }?>></td><td align=left><b><? echo $T['Remote']; ?></b></td><td><? echo $T['Remote Placement']; ?></td>
	</tr>
	<tr class="row2">
		<td></td><td align="right"><b><? echo $T['FTP Server']; ?>: </b></td><td><input type="textbox" name="data[location][server]" value="<? if (empty($data['location']['server'])) echo '127.0.0.1'; else echo $data['location']['server']; ?>"></td>
	</tr>
	<tr class="row2">
		<td></td><td align="right"><b><? echo $T['Username']; ?>: </b></td><td><input type="textbox" name="data[location][username]" value="<? echo $data['location']['username']; ?>"></td>
	</tr>
	<tr class="row2">
		<td></td><td align="right"><b><? echo $T['Password']; ?>: </b></td><td><input type="password" name="data[location][password]" value="<? echo $data['location']['password']; ?>"></td>
	</tr>
	<tr class="row2">
		<td></td><td align="right"><? echo $T['Directory']; ?>: </td><td><input type="textbox" name="data[location][directory]" value="<? echo $data['location']['directory']; ?>"></td>
	</tr>
</table><br>
<div align="center"><input type="submit" value="<? echo $T['Create Backup']; ?>"></div>
</form>
</div>
<?
	break;
	case "del":
	$SQL = "SELECT backups.id as backid, backups.domain, backups.recurrance, backups.files, backups.email, backups.remote, backups.local, backups.cpusername FROM backups INNER JOIN domains on backups.domain = domains.domain WHERE owner=".$resellerdata['id']." ORDER BY backups.domain";
	$selfres = mysql_query($SQL);
?>

<form action="<?=$current_url;?>" method="post" name="webcp" onSubmit="submitonce(this);">
<input type="hidden" name="data[action]" value="delete">
<input type="hidden" name="action" value="del">
<input type="hidden" name="data[deletebackup]" value="yes">

<table align="center" cellpadding="0" cellspacing="1" width="600" class="tblbg">
	<tr class="tbltop">
		<td colspan=9><b>&nbsp;<? echo $T['Select Scheduled Backups']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row2">
		<td></td><td><i><?=$T['Contents'];?></i></td><td align="center"><i><?=$T['Frequency'];?></i></td><td align=center><i><?=$T['Files'];?></i></td><td align=center><i><?=$T['Email'];?></i></td><td align=center><i><?=$T['Remote'];?></i></td><td align="center"><i><?=$T['Local'];?></i></td><td align="center"><i><?=$T['Owner'];?></i></td>
	</tr>
<?
	$backupsFound = false;
	$curclass = "row2";
	for($i=0; $row=mysql_fetch_array($selfres); $i++) {
		$backupsFound = true;
		if ($curclass == "row2") {
			$curclass = "row1";
		} else {
			$curclass = "row2";
		}
		echo "<tr class=".$curclass."><td align=center><input type=checkbox name=data[backups][] value=".$row["backid"]."></td><td>";
		if ($row["domain"] != "") {
			echo $row["domain"];
		} else {
			echo $T['Databases'];
		}
		echo "</td><td align=center>".$row["recurrance"]."</td><td align=center>";
		if ($row["files"]) { echo "X"; } else { echo "-"; }
		echo "</td><td align=center>";
		if ($row["email"]) { echo "X"; } else { echo "-"; }
		echo "</td><td align=center>";
		if ($row["remote"]) { echo "X"; } else { echo "-"; }
		echo "</td><td align=center>";
		if ($row["local"]) { echo "X"; } else { echo "-"; }
		echo "</td><td align=center><a href='?cp=personal&url=userinfo&user=".$row["cpusername"]."'>".$row["cpusername"]."</a></td></tr>";
	}
?>
</table>
<div align="center">
<? if ($backupsFound) { ?>
<br><input type="submit" value="<? echo $T['Delete Backups']; ?>" onclick="return confirm('<?=$T['Confirm Delete Backups'];?>');">
<? } else { ?>
None Found
<? } ?>
</div>
</form>
<?
	$SQL = "SELECT domain FROM domains WHERE owner=".$resellerdata['id']." ORDER BY domain";
	$dres = mysql_query($SQL);
?>
<form action="<?=$current_url;?>" method="post" name="webcp" onSubmit="submitonce(this);">
<input type="hidden" name="data[action]" value="deletelocal">
<input type="hidden" name="action" value="del">
<input type=hidden name="data[deletebackup]" value="yes">

<table align=center cellpadding=0 cellspacing=1 width=600 class="tblbg">
	<tr class="tbltop">
		<td colspan=4><b>&nbsp;<? echo $T['Select Local Backups']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row2">
		<td></td><td><i><?=$T['Contents'];?></i></td><td><i><?=$T['File Name'];?></i></td><td align=center><i><?=$T['File Size'];?></i></td>
	</tr>
<?

	$curclass = "row2";
	$backupsFound = false;
	for($i=0;$row=mysql_fetch_array($dres);$i++) {
		$dirArray = backups_dir_list($cfg['webdir']."/".$row["domain"]."/_backups");
		if (is_array($dirArray)) {
			for($j=0; $j<sizeOf($dirArray); $j++) {
				$backupsFound = true;
				if ($curclass == "row2") {
					$curclass = "row1";
				} else {
					$curclass = "row2";
				}
				echo "<tr class=".$curclass."><td align=center><input type=checkbox name=data[backups][] value='".$cfg['webdir']."/".$row["domain"]."/_backups/".$dirArray[$j]."'></td><td>".$row["domain"]."</td><td>".$dirArray[$j]."</td><td align=center>".return_file_size(filesize($cfg['webdir']."/".$row["domain"]."/_backups/".$dirArray[$j]))."</td></tr>";
			}
		}
	}
?>
</table>
<div align="center">
<? if ($backupsFound) { ?>
<br><input type="submit" value="<? echo $T['Delete Backups']; ?>" onclick="return confirm('<?=$T['Confirm Delete Backups'];?>');">
<? } else { ?>
None Found
<? } ?>
</div>
</form>
<?
	break;
	case "res":
?>

<form action="<?=$current_url;?>" method="post" name="webcp" onSubmit="submitonce(this);">
<input type="hidden" name="data[action]" value="restore">
<input type="hidden" name="action" value="res">
<input type=hidden name="data[restorebackup]" value="yes">
<?
	$SQL = "SELECT domain FROM domains WHERE owner=".$resellerdata['id']." ORDER BY domain";
	$dres = mysql_query($SQL);
?>
<table align=center cellpadding=0 cellspacing=1 width=600 class="tblbg">
	<tr class="tbltop">
		<td colspan=4><b>&nbsp;<? echo $T['Select Local Backups']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row2">
		<td></td><td><i><?=$T['Contents'];?></i></td><td><i><?=$T['File Name'];?></i></td><td align=center><i><?=$T['File Size'];?></i></td>
	</tr>
<?

	$curclass = "row2";
	$backupsFound = false;
	for($i=0;$row=mysql_fetch_array($dres);$i++) {
		$dirArray = backups_dir_list($cfg['webdir']."/".$row["domain"]."/_backups");
		if (is_array($dirArray)) {
			for($j=0; $j<sizeOf($dirArray); $j++) {
				$backupsFound = true;
				if ($curclass == "row2") {
					$curclass = "row1";
				} else {
					$curclass = "row2";
				}
				echo "<tr class=".$curclass."><td align=center><input type=checkbox name=data[backups][] value='".$cfg['webdir']."/".$row["domain"]."/_backups/".$dirArray[$j]."'></td><td>".$row["domain"]."</td><td>".$dirArray[$j]."</td><td align=center>".return_file_size(filesize($cfg['webdir']."/".$row["domain"]."/_backups/".$dirArray[$j]))."</td></tr>";
			}
		}
	}
?>
</table>
<div align="center">
<? if ($backupsFound) { ?>
<br><input type="submit" value="<? echo $T['Restore Backups']; ?>" onclick="return confirm('<?=$T['Confirm Restore Backups'];?>');">
<? } else { ?>
None Found
<? } ?>
</div>
</form>
<?
$SQL = "SELECT domain FROM domains WHERE owner=".$resellerdata['id']." ORDER BY domain";
$dres = mysql_query($SQL);
?>
<Br>
<form action="<?=$current_url;?>" method="post" name="webcp" onSubmit="submitonce(this);" enctype="multipart/form-data">
<input type="hidden" name="data[action]" value="upload">
<input type="hidden" name="action" value="res">
<input type=hidden name="data[uploadbackup]" value="yes">
<table align=center cellpadding=0 cellspacing=1 width=600 class="tblbg">
	<tr class="tbltop">
		<td colspan=4><b>&nbsp;<? echo $T['Upload Remote Backups']; ?>&nbsp;</b></td>
	</tr>
	<tr class="row1">
		<td>Select a Domain: </td>
		<td>
			<select name="domain">
				<option value="">Please Select</option>
				<?
				for($i=0; $row=mysql_fetch_array($dres); $i++) {
					echo "<option value='".$row["domain"]."'>".$row["domain"]."</option>";
				}
				?>
			</select>
		</td>
	</tr>
	<tr class="row2">
		<td>Browse to Backup: </td><td><input type="file" name="backupfile" size=30></td>
	</tr>
</table>
<div align="center">
<br><input type="submit" value="<? echo $T['Upload Backup']; ?>">
</div>
</form>
<?
		break;
}

}

// Function: backups_create()
// Utility:	begin a backup
// Usage:	backups_create(NAME,CONTENTS,LOCATION,SCHEDULE)
// Examples: backups_create("");
// Return:	$error array var or nothing
// Definitions:
//		DATA-TYPE: Domain, User etc
//		NAME: Name of Reseller / Domain to backup
//		CONTENTS: List of items to backup, e-mails, databases etc
//		LOCATION: Location to put backup, ftp server or local server
//		SCHEDULE: When to backup, immediately (once), or a regular schedule
function backups_create($data_type, $name, $contents, $location, $schedule) {
	global $T, $cfg, $userdata;

	$error = false;

	// Check user input and show error if necessary
	if (empty($schedule)) {
		$error[0] = $T['err']['backup']['no backup time'];
		return $error;
	}

	if (($schedule['type'] == 'recurring') && ($schedule['recurrance'] == '')) {
		$error[0] = $T['err']['backup']['no schedule'];
		return $error;
	}

	if (empty($name)) {
		$error[0] = $T['err']['backup']['no domains'];
		return $error;
	}

	if (($contents['files'] != "on") && ($contents['email'] != "on") && ($contents['databases'] != "on")) {
		$error[0] = $T['err']['backup']['no backup content'];
		return $error;
	}

	if (($location['local'] != "on") && ($location['remote'] != "on")) {
		$error[0] = $T['err']['backup']['no backup type'];
		return $error;
	}

	// Test remote FTP server
	if ($location['remote'] == "on") {
		$conn_id = ftp_connect($location['server']);
		if (!$conn_id) {
			$error[0] = $T['err']['backup']['ftp connect failed'];
		}

		$login_result = ftp_login($conn_id, $location['username'], $location['password']);
		if (!$login_result) {
			$error[0] = $T['err']['backup']['ftp login failed'];
		} else {

			if ($location['directory'] != "") {
				$dir_result = ftp_chdir($conn_id, $location['directory']);
				if (!$dir_result) {
					$error[0] = $T['err']['backup']['ftp cd failed'];
				}
			}
		}

		ftp_close($conn_id);
	}

	if ($schedule['type'] == 'immediate') {

		// Need backup manager hook to run as root, no point it starting as non-root and having
		// to commit every single action

		$data['action'] = 'backup';
		$data['type'] = $data_type;
		$data['name'] = $name;
		$data['contents'] = $contents;
		$data['location'] = $location;

		// Simply call the hook backup:run here then all functions will run
		//  backups_backup() will run the backup
		//  backups_package() will package up the backups into one archive
		//  backups_ftp_archive() will ftp the archive

		// Step 1: Commit domain backup as root
		commit('module', "backup:manager|".serialize($data));

	} elseif ($schedule['type'] == 'recurring') {

		($contents['database'] == "on") ? $contents['database'] = 1 : $contents['database'] = 0;
		($contents['files'] == "on") ? $contents['files'] = 1 : $contents['files'] = 0;
		($contents['email'] == "on") ? $contents['email'] = 1 : $contents['email'] = 0;
		($location['local'] == "on") ? $location['local'] = 1 : $location['local'] = 0;
		($location['remote'] == "on") ? $location['remote'] = 1 : $location['remote'] = 0;

		$result = true;
		if (is_array($name_list)) {
			foreach ($name_list as $item) {
				$SQL = "INSERT INTO `backups`(`type`, `name`, `contents`, `location`, `schedule`) VALUES(";
				$SQL .= "'".$data['type']."', '".$data['name']."', '".serialize($contents)."', '".serialize($location)."', '".serialize($schedule)."')";
				$result = mysql_query($SQL);
			}
		}
		if (!$result) {
			$error[0] = $T['err']['backup']['sched fail'] . $SQL;
		}
	}
	return $error;
}

// Function: backups_delete()
// Utility:	delete a backup
// Usage:	backups_delete(TYPE,BACKUPLIST)
// Examples: backups_delete("local","1_2_3");
// Return:	$error	array var or nothing
// Definitions:
//      TYPE: local or scheduled
//      BACKUPLIST: List of backup id's to delete
function backups_delete($type,$backuplist) {
	global $T;
	switch ($type) {
		case "local":
			// Delete a local backup
			for ($i = 0; $i < sizeOf($backuplist); $i++) {
				// this is impossible without root privaledges
				// replace with a delete backup script
				// commit("delete", "$data_type|");
				unlink($backuplist[$i]);
			}
			break;
		case "sched":
			// Delete a scheduled backup
			for ($i = 0; $i < sizeOf($backuplist); $i++) {
				$SQL = "DELETE FROM backups WHERE id = ".$backuplist[$i];
				mysql_query($SQL);
			}
			break;
	}
}

// Function: backups_restore()
// Utility:	restore a backup
// Usage:	backups_restore(TYPE,BACKUPLIST)
// Examples: backups_restore("local","1_2_3");
// Return:	$error	array var or nothing
// Definitions:
//      BACKUPLIST: List of backup id's to delete
function backups_restore($data_type, $backup, $contents, $location) {
	global $T;

	switch ($location['type']) {
		case "local":
			// Restore a local backup
			commit("restore", "$data_type|$backup|$contents|$location");
			break;
		case "remote":
			// Restore a remote backup
			// First check seal
			$error[0] = "Not Yet Implemented";
			return $error;
			break;
	}
}

// Function: backups_dir_list()
// Utility:	list a backup directory
// Usage:	backups_dir_list(DIRECTORY)
// Examples: backups_dir_list("/home/test.com/_backups");
// Return:	$dirarray array var containing list of files
// Definitions:	DIRECTORY: directory to list
function backups_dir_list($directory)
{
	// create an array to hold directory list
	$results = array();
	// create a handler for the directory
	if ($handler = @opendir($directory)) {
		// keep going until all files in directory have been read
		while ($file = readdir($handler)) {
			// if $file isn't this directory or its parent,
			//  add it to the results array
			if ($file != '.' && $file != '..') {
				$results[] = $file;
			}
		}
		// tidy up: close the handler
		closedir($handler);
	} else {
		$results = '';
	}

	return $results;
}

// Manage all aspects of running a physical backup or restore
function backups_manager(&$data) {

	// Unserialize data from frontend
	$data = unserialize($data);

	// Backup or Restore
	switch ($data['action']) {

		case 'backup':
			// Perform a physical backup
			call_hook('server:commit:backup:run', $data);

			// Get all users to backup
			backups_prepare_contents($data, $type);

			// Store this backup, package archives together then ftp
			call_hook('server:commit:backup:store', $data);
			break;

		case 'restore':
			call_hook('server:commit:restore:store', $data);
			call_hook('server:commit:restore:run', $data);
			break;
	}
}

// Recursively find all accounts below a domain/reseller/server
//  For domain - find all users
//  For reseller - find all domains & all users below
//  For server - find all resellers, all domains & all users below
function backups_prepare_contents(&$data, $type) {

	// Find all users for domain, reseller or server
	if ($type == 'domain')
		$sql = "'SELECT username FROM ".$type." WHERE id='".$data['id']."'";
	elseif ($type == 'reseller')
		$sql = "SELECT domain FROM ".$type." WHERE owner='".$data['id']."'";
	elseif ($type == 'server')
		$sql = "SELECT id FROM ".$type;

	$result = mysql_query($sql);
	if ($result) {
		// Loop over users/domains/resellers
		foreach (mysql_fetch_row($result) as $row) {
			if ($type == 'domain') {
				// Get unix username
				$tmp_data['username'] = $row['username'];
				call_hook('user:get:username', $tmp_data);
				// Build user array
				$data['contents']['users'][] = $tmp_data['username'];
			}
			elseif ($type == 'reseller') {
				// Build domain array
				//$tmp_data['name'] = $row['username'];
				$data['contents']['domains'][] = $row['domain'];
				//backups_prepare_contents(&$tmp_data, 'domain');
			}
			elseif ($type == 'server') {
				// Build reseller array
				//$tmp_data['name'] = $row['reseller'];
				$data['contents']['resellers'][] = $row['id'];
				//backups_prepare_contents(&$tmp_data, 'reseller');
			}
		}
		foreach ($data['contents']['domains'] as $domain) {
			// Find users for this domain
			$tmp_data['name'] = $domain;
			backups_prepare_contents($tmp_data, 'domain');
		}
		foreach ($data['contents']['resellers'] as $reseller) {
			// Find domains for this reseller
			$tmp_data['name'] = $reseller;
			backups_prepare_contents($tmp_data, 'reseller');
		}
	} else
		return false;

	return true;
}

// Call hooks for an individual reseller/domain/user backup
function backups_call_hooks(&$data) {

	// Call hooks for this item
	return $data['module_archives'] = call_hook("server:".$data['type'].":backup", $data);
}

// Recursively run backups for sub accounts
function backups_manager_recurse(&$data) {

	// This function is far too complicated, it
	//  needs to just call hooks for the users or do that eleswhere

	webcp_log(3,0,'backup.php',"Backup: Recursing accounts".var_dump($data),0,ECHO_LOG);

	if (sizeOf($data['contents']['users']) > 0) {
		foreach($data['contents']['users'] as $user) {
			// Subdata (we cannot loose the existing data)
			$tmp_data = $data;

			// Step 2: Commit user backups as root
			$tmp_data = array('type' => 'user', 'name' => $user);

			$data['archives'][$data['type']] = call_hook('server:commit:backup:run', $tmp_data);
		}
		webcp_log(3,0,'backup.php',"Backup: Running sub-backups -user",0,ECHO_LOG);
	}

	return $data['archives'][$data['type']];
}

// Recursiveley run backups for sub accounts
function backups_recurse_backups(&$data, $type) {

	if (empty($data['contents'][$type]))
		return false;

	// Recurse contents of backup
	$tmp = $data['contents'][$type];
	// Run backups of those below this domain/reseller
	foreach ($tmp as $backup)
		call_hook('server:commit:backup:run', $backup);
}

// Backup a reseller/domain/user
// all backup code should be in here for cohesion
// Perform one backup
function backups_backup(&$data) {

	global $cfg, $echo;
	define('ECHO_LOG', $echo);

	// Clear variables
	$metadata = '';

	// Log backup started
	webcp_log(3,0,'backup.php',"Backup: Started for ".$data['name'],0,ECHO_LOG);

	// Call hooks for all modules associated with this reseller/domain/user
	$module_archives = backups_call_hooks($data);

	// far far far too complicated
	$archive_file = $data['name'].'_'.time().'.tar';
	$metadata_file = $data['name'].'_metadata.txt';
	$database_file = $data['name'].'_webcp_data.txt';

	// Backup webcp's information for a domain, user etc
	// select from database put in tar
	// For security use if or switch here.
	if ($data['type'] == 'reseller') $sql = "SELECT * FROM resellers LIMIT 1";
	elseif ($data['type'] == 'domain') $sql = "SELECT * FROM domains LIMIT 1";
	elseif ($data['type'] == 'user') $sql = "SELECT * FROM users LIMIT 1";
	// Perform query
	$dbp = mysql_query($sql);
	if (is_resource($dbp)) {
		$database_info = mysql_fetch_row($dbp);
		$database_info = serialize($database_info)."\n";
	}
	// Write webcp information for this domain/user to file
	$fp = file_put_contents('/tmp/'.$database_file, $database_info);
	if (!$fp) {
		webcp_log(3,0,'backup.php',"Backup: Failed for ".$data['name'],0,ECHO_LOG);
		return false;
	}
	// Add webcp information file for this domain/user to metadata
	$metadata .= '/tmp/'.$database_file."\n";

	// Put all the module archives for this user together
	// Run module backups here calling function
	foreach ($module_archives as $module_archive) {
		if (is_file('/tmp/'.$module_archive)) {
			// Add module archive file name to metadata for this backup archive
			$metadata .= '/tmp/'.$module_archive."\n";
			// Add each tar file to the backup archive
			webcp_log(3,0,'backup.php',"Backup: Modules for ".$data['name'],0,ECHO_LOG);
			exec($cfg['prog']['tar']." -rh -C /tmp -f /tmp/".$archive_file." ".$module_archive, $output, $result);
		}
	}

	// Run subbackups here calling function
	backups_recurse_backups($data, 'users');
	//backups_recurse_backups($data, 'domains');
	//backups_recurse_backups($data, 'resellers');

	// Write metadata file for this backup archive
	$fp = file_put_contents('/tmp/'.$metadata_file, $metadata);
	if (!$fp) {
		webcp_log(3,0,'backup.php',"Backup: Failed for ".$data['name'],0,ECHO_LOG);
		return false;
	}

	// Add database information to backup archive
	exec($cfg['prog']['tar']." -rh -C /tmp -f /tmp/".$archive_file." ".$database_file, $output, $result);
	// Add metadata to backup archive
	exec($cfg['prog']['tar']." -rh -C /tmp -f /tmp/".$archive_file." ".$metadata_file, $output, $result);
	// Clean up temporary files
	exec('rm /tmp/'.$metadata_file.' /tmp/'.$database_file);

	// Log successful backup
	webcp_log(3,0,'backup.php',"Backup: Completed for ".$data['name'],0,ECHO_LOG);

	return $archive_file;
}

// Restore a reseller/domain/user
//function backups_restore(&$data) {

//}

// Generate the compressed final backup archive
//  when all else has been done.
function backups_generate_archive(&$data) {

	global $cfg;

	// Add account backups (users for domains, domains for resellers etc) to archive
	$dir = backups_dir_list('/tmp/');
	foreach($dir as $file) {
		if (stristr('.domain.tar', $file))
			$backups[] = $file;
	}
	// take the archives with user in the name as users and add to the directory for backups. this will have some kind of date in the name to validate against

	return true;
}

// FTP Backup to local server or elsewhere
function backups_ftp_archive(&$data) {

	$conn_id = ftp_connect($data['location']['server']);
	if ($conn_id) {
		if (ftp_login($conn_id, $data['location']['username'], $data['location']['password'])) {
			if ($data['location']['directory'] != '')
				ftp_chdir($conn_id, $data['location']['directory']);

			if (!ftp_put($conn_id, $data['archive'], '/tmp/'.$data['archive'], FTP_BINARY)) {
				webcp_log(3,0,'backup.php',"Backup: FTP Failed for ".$data['archive'],0,ECHO_LOG);
				return false;
			}
		}
		ftp_close($conn_id);
	} else {
		webcp_log(3,0,'backup.php',"Backup: Connection failed to ".$data['location']['server'],0,ECHO_LOG);
		return false;
	}

	return true;
}

?>
